<template>
  <div class="bpmn-designer-container">
    <!-- 顶部导航栏 -->
    <div class="designer-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>流程管理</el-breadcrumb-item>
        <el-breadcrumb-item>流程设计</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="action-buttons">
        <el-tag type="success">0 错误</el-tag>
        <el-tag type="warning">0 警告</el-tag>
        <div class="bpmn-brand">BPMN.io</div>
      </div>
    </div>

    <!-- 工具栏 -->
    <Toolbar />

    <div class="designer-content">
      <!-- 左侧工具栏 -->
      <Palette />

      <!-- 中间画布区域 -->
      <BpmnModeler ref="modelerRef" />

      <!-- 右侧属性面板 -->
      <PropertiesPanel />

      <!-- 附加元素菜单 -->
      <AppendMenu ref="appendMenuRef" @element-added="onElementAdded" />
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import Toolbar from '@/components/modeler/Toolbar.vue'
import Palette from '@/components/modeler/Palette.vue'
import BpmnModeler from '@/components/modeler/BpmnModeler.vue'
import PropertiesPanel from '@/components/modeler/PropertiesPanel.vue'
import AppendMenu from "@/components/properties/AppendMenu.vue"

export default {
  name: 'BpmnDesigner',
  components: { Toolbar, Palette, BpmnModeler, PropertiesPanel, AppendMenu },
  setup() {
    const modelerRef = ref(null) // 修复点1：通过ref获取模型器实例
    const appendMenuRef = ref(null)

    // 修复点2：正确的元素点击处理函数
    const handleElementClick = (element, canvas) => {
      if (element.type.includes('Task') || element.type.includes('Gateway')) {
        const bbox = canvas.getAbsoluteBBox(element)
        const viewbox = canvas.viewbox()

        // 计算精确位置
        appendMenuRef.value.show(element,
            bbox.x + bbox.width + 10 - viewbox.x,
            bbox.y - viewbox.y
        )
      }
    }

    onMounted(() => {
      // 修复点3：安全等待组件初始化
      setTimeout(() => {
        if (modelerRef.value) {
          const canvas = modelerRef.value.getCanvas()
          canvas.on('element.click', event => {
            handleElementClick(event.element, canvas)
          })
        }
      }, 300)
    })

    return { modelerRef, appendMenuRef }
  }
}
</script>

<style lang="scss" scoped>
.bpmn-designer-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 20px);
  width: 100%;
  background: #fff;
  padding: 10px;
  position: relative;
}

.designer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px 10px;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 10px;

  .action-buttons {
    display: flex;
    align-items: center;
    gap: 15px;

    .bpmn-brand {
      font-weight: bold;
      color: #409EFF;
      font-size: 14px;
    }
  }
}

.designer-content {
  display: flex;
  flex: 1;
  overflow: hidden;
  position: relative;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
</style>